import { HttpClient } from '@dui/node-http-client';
import { get } from '@dui/node-http-cls';
import { getLogger } from '@dui/node-logger';
import config from 'config';

export default new HttpClient({
  baseUrl: config.get('API_INTRA_BASE_URL'),
  defaultHeadersProvider(url) {
    if (/^https?:/.test(url)) {
      return {};
    }
    return get('PASS_THROUGH_HEADERS') || {};
  },
  // 打印外部请求的 accessLog
  onPostResponse(options, httpRes) {
    const totalTime = httpRes.timingPhases && httpRes.timingPhases.total;
    const logger = getLogger();
    logger.info(
      {
        type: 'access',
        method: options.method,
        url: options.uri,
        ...httpRes.timingPhases,
        latency: Math.round(totalTime),
        statusCode: httpRes.statusCode,
      },
      '%s %s %dms %d',
      options.method,
      options.uri,
      totalTime,
      httpRes.statusCode,
    );

    logger.info(
      'request body %o , response body %o',
      options.json,
      httpRes.result,
    );
  },
});
